package tools

import (
	"crypto/rand"
	"encoding/hex"
	"math/big"
)

// GenerateRandomShortId 生成随机短ID
func GenerateRandomShortId(length int) string {
	if length <= 0 {
		length = 8
	}

	// 生成随机字节
	bytes := make([]byte, (length+1)/2) // hex编码需要一半的字节长度
	if _, err := rand.Read(bytes); err != nil {
		// fallback到时间戳+随机数
		return generateFallbackId(length)
	}

	// 转换为hex字符串并截取指定长度
	hexStr := hex.EncodeToString(bytes)
	if len(hexStr) > length {
		hexStr = hexStr[:length]
	}

	return hexStr
}

func generateFallbackId(length int) string {
	const charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	result := make([]byte, length)

	for i := 0; i < length; i++ {
		n, _ := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
		result[i] = charset[n.Int64()]
	}

	return string(result)
}

// GenerateShortId8 生成8位随机短ID
func ShortId6() string {
	return GenerateRandomShortId(6)
}

// ShortId10 生成10位随机短ID
func ShortId10() string {
	return GenerateRandomShortId(10)
}
